﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System.Threading;
using Autofac;
using Autofac.Core;
using Autofac.Features.OwnedInstances;
using BitwiseOre.SharedMemory.Context;
using BitwiseOre.SharedMemory.Core;
using BitwiseOre.SharedMemory.Core.Common;
using BitwiseOre.SharedMemory.External;
using BitwiseOre.SharedMemory.JetBrains;

namespace BitwiseOre.SharedMemory.Autofac
{
    [UsedImplicitly]
    internal sealed class EventWaitHandleFactory : IEventWaitHandleFactory
    {
        private readonly ILifetimeScope _lifetimeScope;

        public EventWaitHandleFactory(ILifetimeScope lifetimeScope)
        {
            _lifetimeScope = lifetimeScope;
        }

        public Owned<IEventWaitHandle> Create(string name)
        {
            var status = _lifetimeScope.ResolveConfig<IEventWaitHandleConfig>().Status;
            var lifetime = _lifetimeScope.BeginLifetimeScope();
            Owned<IEventWaitHandle> result = null;

            try
            {
                var @event = lifetime.ResolveKeyed<EventWaitHandle>(status, new NamedParameter("name", name));
                var adaptor = lifetime.Resolve<IEventWaitHandle>(new TypedParameter(typeof (EventWaitHandle), @event));
                result = new Owned<IEventWaitHandle>(adaptor, lifetime);
            }
            catch (DependencyResolutionException exception)
            {
                if (exception.InnerException is WaitHandleCannotBeOpenedException)
                {
                    result = null;
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                if (result == null)
                {
                    lifetime.Dispose();
                }
            }
            return result;
        }
    }
}